package com.qinghuan.threads.chapterOne;

import lombok.SneakyThrows;

/**
 * @Author: dubao
 * @Date: 2022/5/16 20:07
 * @Description:
 * notify():调用等待集合中的随机的一个被阻塞的线程
 * notifyAll():调用所有等待集合中的线程，
 * 不加上sleep方法，可能线程A和线程B会在线程C之后被唤醒，就有可能导致线程C中就算执行notifyAll()方法，也不一定都能唤醒的情况
 */
public class test1_3_2 {

    //创建资源
    private static volatile Object resourceA = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取resourceA共享资源的监视器锁
                synchronized (resourceA) {
                    System.out.println("threadA get resourceA lock");
                    try {
                        System.out.println("threadA begin wait");
                        resourceA.wait();
                        System.out.println("threadA end wait");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("threadB get resourceA lock");
                    System.out.println("threadB begin wait");
                    resourceA.wait();
                    System.out.println("threadB end wait");
                }
            }
        });

        Thread threadC = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("threadC get notify");
                    resourceA.notify();
                }
            }
        });

        threadA.start();
        threadB.start();
        Thread.sleep(1000);
        threadC.start();
        //等待线程结束
        threadA.join();
        threadB.join();
        threadC.join();
        System.out.println("main over!");

    }

}
